﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace AuriaCompte.Lib.Dao
{
    public class DaoDb
        : DaoBase
    {
        public DaoDb()
            : base()
        {
            this.TableName = "db";
            this.ViewName = "db";
            this.PrimaryKeyName = "i_db_id";
            this.ListColonne.Add("i_db_id");
            this.ListColonne.Add("IsPasswordProtected");
            this.ListColonne.Add("Password");
        }

        public Db Select()
        {
            lParam.Clear();
            Db retour = new Db();
            String req = this.DebutSelect
                + this.TableName;

            SQLiteDataReader dr = this.ExecuteQueryReader(req, lParam);

            if (dr.Read())
                retour = ChargeFromReader(dr);
            else
            {
                Db d = new Db();
                d.IsPasswordProtected = false;
                d.Password = String.Empty;
                this.Insert(d);
                retour = this.Select();
            }
            dr.Close();
            return retour;
        }

        public Db Insert(Db d)
        {
            lParam.Clear();

            Db retour = new Db();
            String req = "INSERT INTO " + TableName + "(i_db_id, IsPasswordProtected, Password) " +
                "VALUES(NULL, @IsPasswordProtected, @Password)";

            lParam.Add(new SQLiteParameter("@IsPasswordProtected", d.IsPasswordProtected));
            lParam.Add(new SQLiteParameter("@Password", d.Password));
            
            this.ExecuteNonQuery(req, lParam);
            retour = this.Select();

            return retour;
        }

        public Db Update(Db d)
        {
            lParam.Clear();

            Db retour = new Db();
            String req = "UPDATE " + TableName + " SET IsPasswordProtected=@IsPasswordProtected, Password=@PAssword ";

            lParam.Add(new SQLiteParameter("@IsPasswordProtected", d.IsPasswordProtected));
            lParam.Add(new SQLiteParameter("@Password", d.Password));
            
            this.ExecuteNonQuery(req, lParam);
            retour = this.Select();

            return retour;
        }

        private Db ChargeFromReader(SQLiteDataReader dr)
        {
            Db retour = new Db();

            retour.i_db_id = dr.GetInt32(0);
            if (dr.IsDBNull(1))
                retour.IsPasswordProtected = false;
            else
                retour.IsPasswordProtected = dr.GetBoolean(1);
            if (dr.IsDBNull(2))
                retour.Password = String.Empty;
            else
                retour.Password = dr.GetString(2);

            return retour;
        }
    }
}
